import React, { useState, useEffect } from 'react';
import { ViewStyle, TextStyle, View, Text, TouchableOpacity, Modal, Animated, StyleSheet } from 'react-native';

interface ErrorModalProps {
    visible: boolean; // 控制弹窗显示/隐藏
    onClose: () => void; // 关闭弹窗的回调
    errorText: string; // 错误文案
    modalStyle?: ViewStyle; // 弹窗容器样式
    textStyle?: TextStyle; // 错误文案样式
    closeButtonStyle?: ViewStyle; // 关闭按钮样式
    closeButtonTextStyle?: TextStyle; // 关闭按钮文字样式
    closeButtonText?: string; // 关闭按钮文字
}
const ErrorModal: React.FC<ErrorModalProps> = ({
    visible,
    onClose,
    errorText,
    modalStyle,
    textStyle,
    closeButtonStyle,
    closeButtonTextStyle,
    closeButtonText = 'Close',
}) => {
    const [animation] = useState(new Animated.Value(0));

    useEffect(() => {
        if (visible) {
            Animated.timing(animation, {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }).start();
        } else {
            Animated.timing(animation, {
                toValue: 0,
                duration: 300,
                useNativeDriver: true,
            }).start();
        }
    }, [visible]);

    const translateY = animation.interpolate({
        inputRange: [0, 1],
        outputRange: [-100, 0], // 从顶部滑入
    });

    const opacity = animation.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1],
    });

    return (
        <Modal transparent visible={visible} onRequestClose={onClose}>
            <View style={styles.modalOverlay}>
                <Animated.View style={[styles.modalContainer, modalStyle, { transform: [{ translateY }], opacity }]}>
                    <Text style={[styles.errorText, textStyle]}>{errorText}</Text>
                    <TouchableOpacity style={[styles.closeButton, closeButtonStyle]} onPress={onClose}>
                        <Text style={[styles.closeButtonText, closeButtonTextStyle]}>{closeButtonText}</Text>
                    </TouchableOpacity>
                </Animated.View>
            </View>
        </Modal>
    );
};

const styles = StyleSheet.create({
    modalOverlay: {
        flex: 1,
        justifyContent: 'flex-start', // 从顶部开始
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        paddingTop: 50, // 顶部留出空间
    },
    modalContainer: {
        width: '80%',
        backgroundColor: 'white',
        borderRadius: 10,
        padding: 20,
        alignItems: 'center',
    },
    errorText: {
        fontSize: 16,
        color: 'red',
        marginBottom: 20,
        textAlign: 'center',
    },
    closeButton: {
        padding: 10,
        backgroundColor: '#ccc',
        borderRadius: 5,
        alignItems: 'center',
        width: '100%',
    },
    closeButtonText: {
        fontSize: 16,
        color: 'white',
    },
});

export default ErrorModal;
